<?php
/**
 * --------------------------------------------------------------------
 * MCore框架
 * 作者：阿枫，QQ：52037872，Email：nczy520@gmail.com
 * --------------------------------------------------------------------
 *
 * SVN revision information:
 * @version $Revision: 50 $:
 * @author  $Author: zy $:
 * @date      $Date: 2013-11-09 19:34:15 +0800 (星期六, 09 十一月 2013) $:
 * @url         $HeadURL: svn://vps.mdeve.com/web_mcore/manage/function/global.func.php $:
 */

class _MembersClass extends __basic_def {

    private $template_path = "";

    function __construct(){
        $this->template_path = MANAGE_PATH. DIRECTORY_SEPARATOR. "templates";
    }

    /**
     * 用户管理->用户列表
     */
    function _user_list(){
        global $_M, $m, $a;

        $page = intval($_GET["page"] ?? 1);
        if($page < 1) $page = 1;
        $pagenum = 20;

        $_M->db();
        $row = $_M->db->get_row(array("table"=>"user", "field"=>"count(*) as num"));
        $totalnum = $row["num"];

        $row = $_M->db->get_rows(array("table"=>"user", "order"=>"id desc", "page"=>"{$page},{$pagenum}"));
        for($i=0; $i<sizeof($row); $i++) {
            $row[$i]["online_time"] = format_second($row[$i]["online_time"]);
        }

        $breadcrumb = array(
            "用户管理" => "#",
            "用户列表" => "",
        );

        $_M->template();
        $_M->template->load("{$this->template_path}/options/user_list");
        $_M->template->process_block("list", $row);
        $_M->template->set_var("{current_page}", $page);
        $_M->template->insert_html(_generate_breadcrumb($breadcrumb));
        $_M->template->set_var("{pagenav}", _generate_pagenav($totalnum, $pagenum, $page, "?m={$m}&a={$a}"));
        $_M->template->display();
    }

    function _edit() {
        global $_M;

        $id = intval(filter_input(INPUT_GET, "id"));
        $page = intval(filter_input(INPUT_GET, "page"));

        $_M->db();
        if($id > 0) {
            $row = $_M->db->get_row(array("table"=>"user","field"=>"id,user,email,locked", "where"=>"id={$id}"));
        } else {
            $row = array(
                "user" => "",
                "email" => "",
                "locked" => 0
            );
        }


        // 读取用户角色
        $user_role = array();
        if($id) {
            $user_role_data = $_M->db->get_row(array("table" => "user_meta", "field"=>"meta_value", "where"=>"uid={$id} and meta_key='permissions'"));
            if(is_array($user_role_data)) {
                $user_role = json_decode($_M->encrypt->DecodeZ($user_role_data["meta_value"]), true);
            }
        }

        // 读取角色列表
        $roles = $_M->db->get_rows(array("table"=>"user_role"));
        $role_list = "";
        foreach($roles as $r) {
            $role_list .= "<label class=\"form-check-label\"><input type=\"checkbox\" class=\"form-check-input\" name=\"role\" value=\"{$r["id"]}\"" . (in_array($r["id"], $user_role) ? " checked" : "") . "> &nbsp; {$r["name"]}</label><br />";
        }

        $breadcrumb = array(
            "用户管理" => "#",
            ($id ? "编辑" : "添加"). "用户列表" => "",
        );
        $_M->template();
        $_M->template->load("{$this->template_path}/options/user_edit");
        $_M->template->set_vars($row);
        $_M->template->set_var("{role_list}", $role_list);
        $_M->template->set_var("{id}", $id);
        $_M->template->set_var("{page}", $page);
        $_M->template->insert_html(_generate_breadcrumb($breadcrumb));
        $_M->template->display();
    }

    function _edit_save(){
        global $_M;

        $id = intval(filter_input(INPUT_POST, "id"));
        $user = clear_string(filter_input(INPUT_POST, "user"));
        $email = clear_string(filter_input(INPUT_POST, "email"));
        $pass = clear_string(filter_input(INPUT_POST, "pass"));
        $locked = intval(filter_input(INPUT_POST, "locked"));
        $role_ids = clear_string(filter_input(INPUT_POST, "role_ids"));

        if(strlen($user) < 2) ajax_result("error", "登陆名填写太短！");
        if(strlen($pass) && strlen($pass)!=32) ajax_result("error", "密码格式错误！");

        // 检查如果是超级管理员则不允许修改
        if($id && in_array($id, $_M->cfg["Administrator"])) ajax_result("error", "此账户无法修改");

        $_M->db();

        // 检查用户名是否重复
        $row = $_M->db->get_row(array("table"=>"user", "field"=>"count(*) as num", "where"=>"user='{$user}'". ($id ? " and id<>{$id}" : "")));
        if($row["num"]) ajax_result("error", "登陆名已存在！");

        $data = array(
            "user" => $user,
            "email" => $email,
            "locked" => $locked
        );
        if(strlen($pass) == 32) {
            require_once CORE_PATH. '/class/drivers/PasswordHash.php';
            $hasher = new PasswordHash(8, false);
            $data["pass"] = $hasher->HashPassword($pass);
        }

        if($id) {
            $_M->db->update($data, array("table"=>"user", "where"=>"id={$id}"));
        } else {
            $_M->db->insert($data, array("table"=>"user"));
            $id = $_M->db->insert_id();
        }

        $role_ids_array = explode(",", $role_ids);

        $_M->user();
        $_M->user->set_user_meta($id, "permissions", $_M->encrypt->EncodeZ(json_encode($role_ids_array)));

        ajax_result("successful");
    }

    ////////////////////////////////////////////////////////////////////////////////////////
    function _role_list() {
        global $_M, $m, $a;

        $page = intval($_GET["page"] ?? 1);
        if($page < 1) $page = 1;
        $pagenum = 20;

        $_M->db();
        $row = $_M->db->get_row(array("table"=>"user_role", "field"=>"count(*) as num"));
        $totalnum = $row["num"];

        $row = $_M->db->get_rows(array("table"=>"user_role", "id,name,content,updatetime"=>"", "order"=>"id", "page"=>"{$page},{$pagenum}"));

        $breadcrumb = array(
            "用户管理" => "#",
            "角色管理" => "",
        );

        $_M->template();
        $_M->template->load("{$this->template_path}/options/user_role_list");
        $_M->template->process_block("list", $row);
        $_M->template->set_var("{current_page}", $page);
        $_M->template->insert_html(_generate_breadcrumb($breadcrumb));
        $_M->template->set_var("{pagenav}", _generate_pagenav($totalnum, $pagenum, $page, "?m={$m}&a={$a}"));
        $_M->template->display();
    }

    function _role_edit() {
        global $_M;

        $id = intval(filter_input(INPUT_GET, "id"));
        $page = intval(filter_input(INPUT_GET, "page"));

        $_M->db();
        $permissions_current = array();
        if($id > 0) {
            $row = $_M->db->get_row(array("table"=>"user_role", "where"=>"id={$id}"));
            if(false === $row) halt("没有找到角色或角色已被删除！");
            $permissions_current = json_decode($_M->encrypt->DecodeZ($row["permissions"]));
        } else {
            $row = array(
                "name" => "",
                "content" => "",
                "permissions" => array()
            );
        }
        $permissions_list = "";
        foreach($_M->public_permissions as $key=>$intro) {
            $permissions_list .= "<label class=\"form-check-label\"><input type=\"checkbox\" class=\"form-check-input\" name=\"permissions[]\" value=\"{$key}\"" . (in_array($key, $permissions_current) ? " checked" : "") . "> &nbsp; {$intro}</label><br />";
        }

        $breadcrumb = array(
            "角色管理" => "#",
            ($id ? "编辑" : "添加"). "用户列表" => "",
        );
        $_M->template();
        $_M->template->load("{$this->template_path}/options/user_role_edit");
        $_M->template->set_var("{permissions_list}", $permissions_list);
        $_M->template->set_var("{id}", $id);
        $_M->template->set_var("{page}", $page);
        $_M->template->set_vars($row);
        $_M->template->insert_html(_generate_breadcrumb($breadcrumb));
        $_M->template->display();
    }

    function _role_edit_save () {
        global $_M;

        $id = intval(filter_input(INPUT_POST, "id"));
        $name = clear_string(filter_input(INPUT_POST, "name"));
        $content = clear_string(filter_input(INPUT_POST, "content"));
        $permissions = $_POST["permissions"] ?? array();

        if(!strlen($name)) ajax_result("error", "角色名称填写太短！");

        $_M->db();
        $row = $_M->db->get_row(array("table"=>"user_role", "field"=>"count(*) as num", "where"=>"name='{$name}'". ($id ? " and id<>{$id}" : "")));
        if($row["num"]) ajax_result("error", "角色名称已存在！");

        $permissions_string = $_M->encrypt->EncodeZ(json_encode($permissions));

        $data = array(
            "name" => $name,
            "content" => $content,
            "permissions" => $permissions_string,
        );
        if($id) {
            $_M->db->update($data, array("table"=>"user_role", "where"=>"id={$id}"));
        } else {
            $_M->db->insert($data, array("table"=>"user_role"));
        }

        ajax_result("successful");
    }

}